import { useState } from "react";
import { Input, Button, Row, Col, Card, Divider } from "antd";
import { diffWords } from "diff";
import ToolTitle from "@/components/ToolTitle";
import { textToolsData } from "@/components/ToolsData";

const TextComparison = () => {
  const [text1, setText1] = useState("");
  const [text2, setText2] = useState("");
  const [diffs, setDiffs] = useState<
    Array<{
      added?: boolean;
      removed?: boolean;
      value: string;
    }>
  >([]);

  const compareTexts = () => {
    const difference = diffWords(text1, text2);
    setDiffs(difference);
  };

  const renderHighlightedText = () => {
    return (
      <Row gutter={16}>
        <Col span={12}>
          <Card title="文本1差异">
            {diffs.map((part, index) =>
              part.removed ? (
                <span
                  key={index}
                  style={{
                    backgroundColor: "#ffb3ba", // 删除部分红色背景
                    textDecoration: "line-through",
                  }}
                >
                  {part.value}
                </span>
              ) : part.added ? null : (
                <span key={index}>{part.value}</span>
              )
            )}
          </Card>
        </Col>
        <Col span={12}>
          <Card title="文本2差异">
            {diffs.map((part, index) =>
              part.added ? (
                <span
                  key={index}
                  style={{
                    backgroundColor: "#baffc9", // 新增部分绿色背景
                  }}
                >
                  {part.value}
                </span>
              ) : part.removed ? null : (
                <span key={index}>{part.value}</span>
              )
            )}
          </Card>
        </Col>
      </Row>
    );
  };

  return (
    <div>
      <ToolTitle
        title={
          textToolsData.find((item) => item.title === "文本对比")?.title || ""
        }
        description={
          textToolsData.find((item) => item.title === "文本对比")
            ?.description || ""
        }
      />

      <Divider />

      <Row gutter={16}>
        <Col span={12}>
          <Input.TextArea
            rows={8}
            value={text1}
            onChange={(e) => setText1(e.target.value)}
            placeholder="输入第一个文本"
          />
        </Col>
        <Col span={12}>
          <Input.TextArea
            rows={8}
            value={text2}
            onChange={(e) => setText2(e.target.value)}
            placeholder="输入第二个文本"
          />
        </Col>
      </Row>

      <Button
        type="primary"
        onClick={compareTexts}
        style={{ margin: "16px 0" }}
      >
        开始比对
      </Button>

      {diffs.length > 0 && renderHighlightedText()}
    </div>
  );
};

export default TextComparison;
